<script lang="ts" setup>
import { ref, reactive, onMounted, h, watch } from 'vue';
import { 
  Card, Tabs, Form, Select, DatePicker, Button, Space, Input, 
  Table, message, Row, Col 
} from 'ant-design-vue';
import {
  SvgCardIcon,
  SvgDownloadIcon,
} from '@vben/icons';
import type { TableColumnsType } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import { 
  getCompanyStatisticsApi, 
  getFreelancerStatisticsApi,
  exportCompanyDataApi,
  exportFreelancerDataApi,
  type DataCenterApi 
} from '#/api/core/data-center';
import { getLandingCompanyOptionsApi, type InvoiceApi } from '#/api/core/invoice';

// 时间选择选项
const timeRangeOptions = [
  { value: 'day', label: '日' },
  { value: 'week', label: '周' },
  { value: 'month', label: '月' },
  { value: 'year', label: '年' },
  { value: 'custom', label: '自定义区间' }
];

// 当前激活的tab
const activeTab = ref('company');

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const companyDataSource = ref<DataCenterApi.CompanyStatisticsRecord[]>([]);
const freelancerDataSource = ref<DataCenterApi.FreelancerStatisticsRecord[]>([]);
const landingCompanyOptions = ref<InvoiceApi.LandingCompanyOption[]>([]);

// 搜索表单 - 结算统计
const companySearchForm = reactive({
  time_range: 'month' as string,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
  landing_company_id: undefined as number | undefined,
});

// 搜索表单 - 自由职业者结算统计
const freelancerSearchForm = reactive({
  time_range: 'month' as string,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
  freelancer_name: '',
  freelancer_phone: '',
  freelancer_id_card: '',
  landing_company_id: undefined as number | undefined,
});

// 分页数据 - 结算统计
const companyPagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 分页数据 - 自由职业者结算统计
const freelancerPagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 初始化时间范围
const initTimeRange = () => {
  const today = dayjs();
  const startOfMonth = today.startOf('month');
  const endOfMonth = today.endOf('month');
  
  companySearchForm.start_date = startOfMonth.format('YYYY-MM-DD');
  companySearchForm.end_date = endOfMonth.format('YYYY-MM-DD');
  
  freelancerSearchForm.start_date = startOfMonth.format('YYYY-MM-DD');
  freelancerSearchForm.end_date = endOfMonth.format('YYYY-MM-DD');
};

// 监听时间范围选择变化
watch(() => companySearchForm.time_range, (newRange) => {
  updateDateRange(newRange, 'company');
});

watch(() => freelancerSearchForm.time_range, (newRange) => {
  updateDateRange(newRange, 'freelancer');
});

// 更新日期范围
const updateDateRange = (range: string, type: 'company' | 'freelancer') => {
  const today = dayjs();
  let startDate: Dayjs;
  let endDate: Dayjs;
  
  switch (range) {
    case 'day':
      startDate = today.startOf('day');
      endDate = today.endOf('day');
      break;
    case 'week':
      startDate = today.startOf('week');
      endDate = today.endOf('week');
      break;
    case 'month':
      startDate = today.startOf('month');
      endDate = today.endOf('month');
      break;
    case 'year':
      startDate = today.startOf('year');
      endDate = today.endOf('year');
      break;
    case 'custom':
      // 自定义区间时不自动设置，由用户手动选择
      return;
    default:
      startDate = today.startOf('month');
      endDate = today.endOf('month');
  }
  
  if (type === 'company') {
    companySearchForm.start_date = startDate.format('YYYY-MM-DD');
    companySearchForm.end_date = endDate.format('YYYY-MM-DD');
  } else {
    freelancerSearchForm.start_date = startDate.format('YYYY-MM-DD');
    freelancerSearchForm.end_date = endDate.format('YYYY-MM-DD');
  }
};

// 落地公司统计表格列定义
const companyColumns: TableColumnsType<DataCenterApi.CompanyStatisticsRecord> = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 120,
  },
  {
    title: '落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
    width: 200,
    ellipsis: true,
  },
  {
    title: '结算成功笔数',
    dataIndex: 'success_count',
    key: 'success_count',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `${text}笔`,
  },
  {
    title: '总金额',
    dataIndex: 'total_amount',
    key: 'total_amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '佣金',
    dataIndex: 'total_commission',
    key: 'total_commission',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '费率',
    dataIndex: 'avg_fee_rate',
    key: 'avg_fee_rate',
    width: 80,
    align: 'center',
  },
  {
    title: '服务费',
    dataIndex: 'total_service_fee',
    key: 'total_service_fee',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '退票金额',
    dataIndex: 'refund_amount',
    key: 'refund_amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  }
];

// 自由职业者统计表格列定义
const freelancerColumns: TableColumnsType<DataCenterApi.FreelancerStatisticsRecord> = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 120,
  },
  {
    title: '姓名',
    dataIndex: 'freelancer_name',
    key: 'freelancer_name',
    width: 100,
  },
  {
    title: '手机号',
    dataIndex: 'freelancer_phone',
    key: 'freelancer_phone',
    width: 120,
  },
  {
    title: '身份证号',
    dataIndex: 'freelancer_id_card',
    key: 'freelancer_id_card',
    width: 150,
  },
  {
    title: '结算成功笔数',
    dataIndex: 'success_count',
    key: 'success_count',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `${text}笔`,
  },
  {
    title: '总金额',
    dataIndex: 'total_amount',
    key: 'total_amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '佣金',
    dataIndex: 'total_commission',
    key: 'total_commission',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '费率',
    dataIndex: 'avg_fee_rate',
    key: 'avg_fee_rate',
    width: 80,
    align: 'center',
  },
  {
    title: '服务费',
    dataIndex: 'total_service_fee',
    key: 'total_service_fee',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '退票金额',
    dataIndex: 'refund_amount',
    key: 'refund_amount',
    width: 120,
    align: 'right',
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  }
];

// 获取落地公司选项
const fetchLandingCompanyOptions = async () => {
  try {
    const response = await getLandingCompanyOptionsApi();
    landingCompanyOptions.value = response || [];
  } catch (error) {
    console.error('获取落地公司选项失败:', error);
  }
};

// 获取落地公司统计数据
const fetchCompanyStatistics = async () => {
  if (!companySearchForm.start_date || !companySearchForm.end_date) {
    message.error('请选择查询时间范围');
    return;
  }
  
  try {
    loading.value = true;
    
    const params: DataCenterApi.StatisticsParams = {
      page: companyPagination.current,
      per_page: companyPagination.pageSize,
      start_date: companySearchForm.start_date,
      end_date: companySearchForm.end_date,
      landing_company_id: companySearchForm.landing_company_id,
    };
    
    console.log('📤 发送落地公司统计请求参数:', params);
    
    const response = await getCompanyStatisticsApi(params);
    console.log('📥 落地公司统计API响应:', response);
    
    companyDataSource.value = response.data || [];
    companyPagination.total = response.total || 0;
    companyPagination.current = response.current_page || 1;

    console.log('✅ 落地公司统计数据更新成功:', {
      count: companyDataSource.value.length,
      total: companyPagination.total,
      current: companyPagination.current
    });
  } catch (error) {
    console.error('❌ 落地公司统计请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    companyDataSource.value = [];
    companyPagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取自由职业者统计数据
const fetchFreelancerStatistics = async () => {
  if (!freelancerSearchForm.start_date || !freelancerSearchForm.end_date) {
    message.error('请选择查询时间范围');
    return;
  }
  
  try {
    loading.value = true;
    
    const params: DataCenterApi.FreelancerStatisticsParams = {
      page: freelancerPagination.current,
      per_page: freelancerPagination.pageSize,
      start_date: freelancerSearchForm.start_date,
      end_date: freelancerSearchForm.end_date,
      freelancer_name: freelancerSearchForm.freelancer_name.trim() || undefined,
      freelancer_phone: freelancerSearchForm.freelancer_phone.trim() || undefined,
      freelancer_id_card: freelancerSearchForm.freelancer_id_card.trim() || undefined,
      landing_company_id: freelancerSearchForm.landing_company_id,
    };
    
    console.log('📤 发送自由职业者统计请求参数:', params);
    
    const response = await getFreelancerStatisticsApi(params);
    console.log('📥 自由职业者统计API响应:', response);
    
    freelancerDataSource.value = response.data || [];
    freelancerPagination.total = response.total || 0;
    freelancerPagination.current = response.current_page || 1;

    console.log('✅ 自由职业者统计数据更新成功:', {
      count: freelancerDataSource.value.length,
      total: freelancerPagination.total,
      current: freelancerPagination.current
    });
  } catch (error) {
    console.error('❌ 自由职业者统计请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    freelancerDataSource.value = [];
    freelancerPagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  if (activeTab.value === 'company') {
    companyPagination.current = 1;
    fetchCompanyStatistics();
  } else {
    freelancerPagination.current = 1;
    fetchFreelancerStatistics();
  }
};

// 重置搜索条件
const handleReset = () => {
  if (activeTab.value === 'company') {
    companySearchForm.time_range = 'month';
    companySearchForm.landing_company_id = undefined;
    initTimeRange();
    companyPagination.current = 1;
    fetchCompanyStatistics();
  } else {
    freelancerSearchForm.time_range = 'month';
    freelancerSearchForm.freelancer_name = '';
    freelancerSearchForm.freelancer_phone = '';
    freelancerSearchForm.freelancer_id_card = '';
    freelancerSearchForm.landing_company_id = undefined;
    initTimeRange();
    freelancerPagination.current = 1;
    fetchFreelancerStatistics();
  }
};

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    if (activeTab.value === 'company') {
      if (!companySearchForm.start_date || !companySearchForm.end_date) {
        message.error('请选择查询时间范围');
        return;
      }
      
      const params: DataCenterApi.StatisticsParams = {
        start_date: companySearchForm.start_date,
        end_date: companySearchForm.end_date,
        landing_company_id: companySearchForm.landing_company_id,
      };
      
      await exportCompanyDataApi(params);
      message.success('导出请求已提交，请稍后下载');
    } else {
      if (!freelancerSearchForm.start_date || !freelancerSearchForm.end_date) {
        message.error('请选择查询时间范围');
        return;
      }
      
      const params: DataCenterApi.FreelancerStatisticsParams = {
        start_date: freelancerSearchForm.start_date,
        end_date: freelancerSearchForm.end_date,
        freelancer_name: freelancerSearchForm.freelancer_name.trim() || undefined,
        freelancer_phone: freelancerSearchForm.freelancer_phone.trim() || undefined,
        freelancer_id_card: freelancerSearchForm.freelancer_id_card.trim() || undefined,
        landing_company_id: freelancerSearchForm.landing_company_id,
      };
      
      await exportFreelancerDataApi(params);
      message.success('导出请求已提交，请稍后下载');
    }
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败，请稍后重试');
  } finally {
    exportLoading.value = false;
  }
};

// 分页变化处理
const handleCompanyTableChange = (paginationParams: any) => {
  companyPagination.current = paginationParams.current;
  companyPagination.pageSize = paginationParams.pageSize;
  fetchCompanyStatistics();
};

const handleFreelancerTableChange = (paginationParams: any) => {
  freelancerPagination.current = paginationParams.current;
  freelancerPagination.pageSize = paginationParams.pageSize;
  fetchFreelancerStatistics();
};

// 自定义日期范围选择处理 - 落地公司
const handleCompanyDateRangeChange = (dates: any, dateStrings: string[]) => {
  companySearchForm.start_date = dateStrings[0] || undefined;
  companySearchForm.end_date = dateStrings[1] || undefined;
};

// 自定义日期范围选择处理 - 自由职业者
const handleFreelancerDateRangeChange = (dates: any, dateStrings: string[]) => {
  freelancerSearchForm.start_date = dateStrings[0] || undefined;
  freelancerSearchForm.end_date = dateStrings[1] || undefined;
};

// Tab变化处理
const handleTabChange = (key: string) => {
  activeTab.value = key;
  // 切换tab时加载对应数据
  if (key === 'company') {
    fetchCompanyStatistics();
  } else {
    fetchFreelancerStatistics();
  }
};

// 组件挂载时初始化
onMounted(() => {
  initTimeRange();
  fetchLandingCompanyOptions();
  fetchCompanyStatistics(); // 默认加载落地公司统计
});
</script>

<template>
  <div class="p-5">
    <Card>
      <Tabs :activeKey="activeTab" @change="handleTabChange">
        <!-- 结算统计 Tab -->
        <Tabs.TabPane key="company" tab="结算统计">
          <!-- 查询区域 -->
          <div class="mb-4">
            <Form layout="inline" :model="companySearchForm">
              <Form.Item label="选择时间" name="time_range">
                <Select
                  v-model:value="companySearchForm.time_range"
                  style="width: 120px"
                >
                  <Select.Option 
                    v-for="option in timeRangeOptions" 
                    :key="option.value" 
                    :value="option.value"
                  >
                    {{ option.label }}
                  </Select.Option>
                </Select>
              </Form.Item>
              
              <Form.Item label="日期区间" name="date_range">
                <DatePicker.RangePicker
                  v-if="companySearchForm.time_range === 'custom'"
                  style="width: 280px"
                  @change="handleCompanyDateRangeChange"
                  :value="[
                    companySearchForm.start_date ? dayjs(companySearchForm.start_date) : null,
                    companySearchForm.end_date ? dayjs(companySearchForm.end_date) : null
                  ]"
                />
                <DatePicker
                  v-else-if="companySearchForm.time_range === 'day'"
                  style="width: 160px"
                  :value="companySearchForm.start_date ? dayjs(companySearchForm.start_date) : null"
                  @change="(date: any, dateString: string) => {
                    companySearchForm.start_date = dateString;
                    companySearchForm.end_date = dateString;
                  }"
                />
                <DatePicker
                  v-else-if="companySearchForm.time_range === 'week'"
                  style="width: 160px"
                  picker="week"
                  :value="companySearchForm.start_date ? dayjs(companySearchForm.start_date).startOf('week') : null"
                  @change="(date: any) => {
                    if (date) {
                      companySearchForm.start_date = date.startOf('week').format('YYYY-MM-DD');
                      companySearchForm.end_date = date.endOf('week').format('YYYY-MM-DD');
                    }
                  }"
                />
                <DatePicker
                  v-else-if="companySearchForm.time_range === 'month'"
                  style="width: 160px"
                  picker="month"
                  :value="companySearchForm.start_date ? dayjs(companySearchForm.start_date).startOf('month') : null"
                  @change="(date: any) => {
                    if (date) {
                      companySearchForm.start_date = date.startOf('month').format('YYYY-MM-DD');
                      companySearchForm.end_date = date.endOf('month').format('YYYY-MM-DD');
                    }
                  }"
                />
                <DatePicker
                  v-else-if="companySearchForm.time_range === 'year'"
                  style="width: 160px"
                  picker="year"
                  :value="companySearchForm.start_date ? dayjs(companySearchForm.start_date).startOf('year') : null"
                  @change="(date: any) => {
                    if (date) {
                      companySearchForm.start_date = date.startOf('year').format('YYYY-MM-DD');
                      companySearchForm.end_date = date.endOf('year').format('YYYY-MM-DD');
                    }
                  }"
                />
              </Form.Item>
              
              <Form.Item label="落地公司" name="landing_company_id">
                <Select
                  v-model:value="companySearchForm.landing_company_id"
                  placeholder="请选择落地公司"
                  style="width: 160px"
                  allowClear
                >
                  <Select.Option 
                    v-for="company in landingCompanyOptions" 
                    :key="company.value" 
                    :value="company.value"
                  >
                    {{ company.label }}
                  </Select.Option>
                </Select>
              </Form.Item>
              
              <Form.Item>
                <Space>
                  <Button 
                    type="primary" 
                    @click="handleSearch"
                    :loading="loading"
                  >
                    查询
                  </Button>
                  <Button 
                    @click="handleReset"
                    :icon="h(SvgCardIcon)"
                  >
                    重置
                  </Button>
                  <Button 
                    @click="handleExport"
                    :icon="h(SvgDownloadIcon)"
                    :loading="exportLoading"
                  >
                    导出数据
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
          
          <!-- 数据表格 -->
          <Table
            :columns="companyColumns"
            :data-source="companyDataSource"
            :loading="loading"
            :pagination="companyPagination"
            row-key="date"
            :scroll="{ x: 1000 }"
            @change="handleCompanyTableChange"
          />
        </Tabs.TabPane>

        <!-- 自由职业者结算统计 Tab -->
        <Tabs.TabPane key="freelancer" tab="自由职业者结算统计">
          <!-- 查询区域 -->
          <div class="mb-4">
            <Row :gutter="16">
              <Col :span="24">
                <Form layout="inline" :model="freelancerSearchForm">
                  <Form.Item label="选择时间" name="time_range">
                    <Select
                      v-model:value="freelancerSearchForm.time_range"
                      style="width: 120px"
                    >
                      <Select.Option 
                        v-for="option in timeRangeOptions" 
                        :key="option.value" 
                        :value="option.value"
                      >
                        {{ option.label }}
                      </Select.Option>
                    </Select>
                  </Form.Item>
                  
                  <Form.Item label="日期区间" name="date_range">
                    <DatePicker.RangePicker
                      v-if="freelancerSearchForm.time_range === 'custom'"
                      style="width: 280px"
                      @change="handleFreelancerDateRangeChange"
                      :value="[
                        freelancerSearchForm.start_date ? dayjs(freelancerSearchForm.start_date) : null,
                        freelancerSearchForm.end_date ? dayjs(freelancerSearchForm.end_date) : null
                      ]"
                    />
                    <DatePicker
                      v-else-if="freelancerSearchForm.time_range === 'day'"
                      style="width: 160px"
                      :value="freelancerSearchForm.start_date ? dayjs(freelancerSearchForm.start_date) : null"
                      @change="(date: any, dateString: string) => {
                        freelancerSearchForm.start_date = dateString;
                        freelancerSearchForm.end_date = dateString;
                      }"
                    />
                    <DatePicker
                      v-else-if="freelancerSearchForm.time_range === 'week'"
                      style="width: 160px"
                      picker="week"
                      :value="freelancerSearchForm.start_date ? dayjs(freelancerSearchForm.start_date).startOf('week') : null"
                      @change="(date: any) => {
                        if (date) {
                          freelancerSearchForm.start_date = date.startOf('week').format('YYYY-MM-DD');
                          freelancerSearchForm.end_date = date.endOf('week').format('YYYY-MM-DD');
                        }
                      }"
                    />
                    <DatePicker
                      v-else-if="freelancerSearchForm.time_range === 'month'"
                      style="width: 160px"
                      picker="month"
                      :value="freelancerSearchForm.start_date ? dayjs(freelancerSearchForm.start_date).startOf('month') : null"
                      @change="(date: any) => {
                        if (date) {
                          freelancerSearchForm.start_date = date.startOf('month').format('YYYY-MM-DD');
                          freelancerSearchForm.end_date = date.endOf('month').format('YYYY-MM-DD');
                        }
                      }"
                    />
                    <DatePicker
                      v-else-if="freelancerSearchForm.time_range === 'year'"
                      style="width: 160px"
                      picker="year"
                      :value="freelancerSearchForm.start_date ? dayjs(freelancerSearchForm.start_date).startOf('year') : null"
                      @change="(date: any) => {
                        if (date) {
                          freelancerSearchForm.start_date = date.startOf('year').format('YYYY-MM-DD');
                          freelancerSearchForm.end_date = date.endOf('year').format('YYYY-MM-DD');
                        }
                      }"
                    />
                  </Form.Item>
                  
                  <Form.Item label="姓名" name="freelancer_name">
                    <Input
                      v-model:value="freelancerSearchForm.freelancer_name"
                      placeholder="请输入姓名"
                      style="width: 120px"
                      allowClear
                      @pressEnter="handleSearch"
                    />
                  </Form.Item>
                  
                  <Form.Item label="手机号" name="freelancer_phone">
                    <Input
                      v-model:value="freelancerSearchForm.freelancer_phone"
                      placeholder="请输入手机号"
                      style="width: 140px"
                      allowClear
                      @pressEnter="handleSearch"
                    />
                  </Form.Item>
                  
                  <Form.Item label="身份证号" name="freelancer_id_card">
                    <Input
                      v-model:value="freelancerSearchForm.freelancer_id_card"
                      placeholder="请输入身份证号"
                      style="width: 160px"
                      allowClear
                      @pressEnter="handleSearch"
                    />
                  </Form.Item>
                  
                  <Form.Item label="落地公司" name="landing_company_id">
                    <Select
                      v-model:value="freelancerSearchForm.landing_company_id"
                      placeholder="请选择落地公司"
                      style="width: 160px"
                      allowClear
                    >
                      <Select.Option 
                        v-for="company in landingCompanyOptions" 
                        :key="company.value" 
                        :value="company.value"
                      >
                        {{ company.label }}
                      </Select.Option>
                    </Select>
                  </Form.Item>
                  
                  <Form.Item>
                    <Space>
                      <Button 
                        type="primary" 
                        @click="handleSearch"
                        :loading="loading"
                      >
                        查询
                      </Button>
                      <Button 
                        @click="handleReset"
                        :icon="h(SvgCardIcon)"
                      >
                        重置
                      </Button>
                      <Button 
                        @click="handleExport"
                        :icon="h(SvgDownloadIcon)"
                        :loading="exportLoading"
                      >
                        导出数据
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              </Col>
            </Row>
          </div>
          
          <!-- 数据表格 -->
          <Table
            :columns="freelancerColumns"
            :data-source="freelancerDataSource"
            :loading="loading"
            :pagination="freelancerPagination"
            row-key="date"
            :scroll="{ x: 1200 }"
            @change="handleFreelancerTableChange"
          />
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>